import java.util.ArrayList;
import java.util.List;

public class Solution {
    public List<List<Integer>> combinationSum3(int k, int n) {
        List<List<Integer>> ans = new ArrayList<>();
        List<Integer> temp = new ArrayList<>();
        backtrack(ans, temp, k, n, 1);
        return ans;
    }

    private void backtrack(List<List<Integer>> ans, List<Integer> temp, int k, int n, int start) {
        if (k == 0 && n == 0) {
            ans.add(new ArrayList<>(temp));
            return;
        }
        if (k == 0 || n < 0) {
            return;
        }
        for (int i = start; i <= 9; i++) {
            temp.add(i);
            backtrack(ans, temp, k - 1, n - i, i + 1);
            temp.remove(temp.size() - 1);
        }
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        int k = 3; // 组合中数字的个数
        int n = 9; // 组合中数字的和
        List<List<Integer>> result = solution.combinationSum3(k, n);
        System.out.println(result);
    }
}